<template>
    <section>
        <kheader :title="friendName"></kheader>
        <div class="wrapper" ref="wrapper">
            <div>
                <sent-msg v-for="(msg,index) in msgArray" :key="index" :sending="msg.send">
                    <template v-slot:msgContent>
                        <p v-html="msg.text"></p>
                    </template>
                </sent-msg>
            </div>
        </div>
        <cube-input class="msg-input" v-model="inputMsg">
            <template v-slot:append>
                <cube-button @click="sendMsg()">Send</cube-button>
            </template>
        </cube-input>
    </section>
</template>

<script>
    import SentMsg from '../components/SentMsg'
    import Header from '../components/Header'

    export default {
        components:{
            SentMsg,
            'kheader':Header
        },
        data () {
            return {
                msgArray:[{send:true,text:'<span>123</span>'},{send:false,text:'<span style="color:red">1233333333333333333333333333333333333333333333</span>'}],
                friendName: 'kyon',
                inputMsg:''
            }
        },
        methods:{
            initWebSocket(){
                this.$ws.setWs(new WebSocket(window.axiosOptions.WS_BASE_URL));
                this.$ws.websock.onmessage = this.wsonmsg;
                this.$ws.websock.onopen = this.wsonopen;
                this.$ws.websock.onerror = this.wsonerror;
                this.$ws.websock.onclose = this.wsonclose;
            },
            wsonopen(){
                let data = { from:'shion', to:'kyon'};
                this.wssend(JSON.stringify(data));
            },
            wsonerror(){
                this.initWebSocket();
            },
            wsonmsg(e){
                let msg = JSON.parse(e.data);
                msg.send = !msg.send;
                this.msgArray.push(msg);
                this.scroll.scrollTo(0, this.scroll.maxScrollY);
            },
            wssend(data){
                this.$ws.websock.send(data);
            },
            wsonclose(e){
                console.log('断开连接',e);
            },
            sendMsg(){
                if(!this.inputMsg){
                    return;
                }
                let msg = {send:true, text: this.inputMsg, from: 'shion', to: 'kyon'};
                this.msgArray.push(msg);
                this.scroll.scrollTo(0, this.scroll.maxScrollY);
                this.wssend(JSON.stringify(msg));
            }
        },
        created(){
            this.initWebSocket();
        },
        mounted(){
            this.$nextTick(() => {
                this.scroll = this.$BScroll(this.$refs.wrapper, {
                    click: true
                });
            })
        },
        beforeDestroy(){
            this.$ws.websock.close();
        }
    }
</script>
<style lang="stylus" scoped>
    .msg-input{
        width: 100%;
        position: absolute;
        bottom: 0;
    }
</style>